import { tireList, tireDetail, tireAdd, tireEdit, carList, deleteTire } from '@/services/tire';
// import { carList } from '@/services/manageCar';
import prompt from '@/components/Prompt';

export default {
  namespace: 'tire',

  state: {
    tireList: {},
    detail: {},
    carList: {},
  },

  effects: {
    *carList({ payload }, { call, put }) {
      const response = yield call(carList, payload);
      if (response.code === 0) {
        const { list, pageSize, total, pageNum } = response.data;
        yield put({
          type: 'cars',
          payload: {
            carList: {
              pagination: {
                current: pageNum,
                pageSize,
                total,
              },
              list,
            },
          },
        });
      }
    },
    *tireList({ payload, callback }, { call, put }) {
      const response = yield call(tireList, payload);
      if (response.code === 0) {
        const { list, pageSize, total, pageNum } = response.data;
        yield put({
          type: 'list',
          payload: {
            tireList: {
              pagination: {
                current: pageNum,
                pageSize,
                total,
              },
              list,
            },
          },
        });
        callback && callback(list);
      }
    },
    *tireDetail({ payload, callback }, { call, put }) {
      const response = yield call(tireDetail, payload);
      if (response.code === 0) {
        yield put({
          type: 'detail',
          payload: {
            detail: { [payload.id]: response.data },
          },
        });
        callback && callback(response.data);
      }
    },
    *tireOperate({ payload, callback }, { call }) {
      const response = yield call(payload.id ? tireEdit : tireAdd, payload);
      const message = payload.id ? `编辑${response.message}` : `新增${response.message}`;
      if (response.code === 0) {
        prompt({ content: message });
        if (callback) callback(response.data);
      }
    },
    *deleteTire({ payload, callback }, { call }) {
      const response = yield call(deleteTire, payload);
      const { code, message } = response;
      if (code === 0) {
        prompt({ content: `删除${message}` });
        callback && callback();
      }
    },
  },

  reducers: {
    cars(state, { payload }) {
      return {
        ...state,
        carList: payload.carList,
      };
    },
    list(state, { payload }) {
      return {
        ...state,
        tireList: payload.tireList,
      };
    },
    detail(state, { payload }) {
      return {
        ...state,
        detail: { ...state.detail, ...payload.detail },
      };
    },
  },
};
